package ru.spb.osll.myfit.fixtures.base;

import java.lang.reflect.Method;
import java.util.List;

import ru.spb.osll.myfit.util.CollectionUtils;
import fit.Fixture;
import fit.Parse;

public class OneLineFixture extends Fixture {
  private Parse resultCell = null;

  @Override
  public void doTable(Parse table) {
    try {
      resultCell = table.at(0, 0, 0);
      List<String> oneLineTable = OneLineFixtureUtils.getOneLineTable(table, args);
      String methodName = OneLineFixtureUtils.getMethodName(oneLineTable);
      Method method = OneLineFixtureUtils.getMethod(getClass(), methodName);
      List<String> paramValues = CollectionUtils.filterOdd(oneLineTable);
      FixtureMethodResult res = OneLineFixtureUtils.invokeMethod(this, method, paramValues);
      if (res == FixtureMethodResult.OK) {
        reportOk();
      } else if (res == FixtureMethodResult.ERROR) {
        reportError();
      }
    } 
    catch (RuntimeException e) {
      e.printStackTrace();
      if (resultCell != null) {
        exception(resultCell, e);
      }
      throw e;
    } catch (InterruptedException e) {
      e.printStackTrace();
      if (resultCell != null) {
        exception(resultCell, e);
      }
      throw new RuntimeException(e);
    }catch (Exception e) {
      e.printStackTrace();
      if (resultCell != null) {
        exception(resultCell, e);
      }
    } catch (LinkageError e) {
      e.printStackTrace();
      if (resultCell != null) {
        exception(resultCell, e);
      }
    }
    catch (Error e) {
      e.printStackTrace();
      if (resultCell != null) {
        exception(resultCell, e);
      }
      throw e;
    }
  }

  private void reportOk() {
    right(resultCell);
  }

  private void reportError() {
    wrong(resultCell);
  }

}